<script setup lang="ts">
import CustomMessage from '@/components/CustomMessage/index.vue';
import { onReachBottom } from '@dcloudio/uni-app';
import { ref } from 'vue';

const isRefreshing = ref(false);
const isLoading = ref(false);
const hasMore = ref(true);
const message = ref();

// 模拟历史记录数据（增加浏览时间字段）
const history = ref([
  {
    id: 1,
    title: 'Vue3 Composition API最佳实践：从入门到精通的全方位指南',
    author: '前端小王子',
    avatar: '/static/images/avatar.png',
    readTime: '5分钟',
    cover: '/static/images/covers/1.jpg',
    category: '前端开发',
    viewTime: '2024-08-15 14:30',
    isRead: true, // 是否已读状态
  },
  {
    id: 2,
    title: 'TypeScript类型体操进阶指南：打造类型安全的现代前端应用',
    author: 'TS大神',
    avatar: '/static/images/avatar.png',
    readTime: '8分钟',
    cover: '/static/images/covers/2.jpg',
    category: '前端开发',
    viewTime: '2024-08-15 10:15',
    isRead: false, // 未读状态
  },
  {
    id: 3,
    title: 'UniApp跨平台开发实战：一次编写多端发布的技巧与经验',
    author: '跨端开发专家',
    avatar: '/static/images/avatar.png',
    readTime: '10分钟',
    cover: '/static/images/covers/3.jpg',
    category: '移动开发',
    viewTime: '2024-08-14 18:45',
    isRead: true,
  },
]);

// 下拉刷新
function onPullDownRefresh() {
  isRefreshing.value = true;
  setTimeout(() => {
    isRefreshing.value = false;
    uni.stopPullDownRefresh();
    message.value.show({
      type: 'success',
      title: '刷新成功',
      message: `已加载${history.value.length}条记录`,
      duration: 1000,
    });
  }, 1000);
}

// 上拉加载更多
onReachBottom(() => {
  if (!hasMore.value || isLoading.value)
    return;

  isLoading.value = true;
  uni.showLoading({ title: '加载历史记录...' });

  setTimeout(() => {
    history.value.push(
      ...[
        {
          id: 4,
          title: 'Tailwind CSS实战技巧：打造高效美观的现代UI界面',
          author: 'CSS魔法师',
          avatar: '/static/images/avatar.png',
          readTime: '6分钟',
          cover: '/static/images/covers/4.jpg',
          category: '前端开发',
          viewTime: '2024-08-14 15:20',
          isRead: true,
        },
      ],
    );
    hasMore.value = history.value.length < 10;
    isLoading.value = false;
    uni.hideLoading();
  }, 1500);
});

// 跳转文章详情
function navigateToDetail(id: number) {
  // 标记为已读
  const item = history.value.find(item => item.id === id);
  if (item)
    item.isRead = true;

  uni.navigateTo({
    url: `/pages/article/detail?id=${id}&from=history`,
  });
}

// 清空历史记录
function clearHistory() {
  uni.showModal({
    title: '提示',
    content: '确定要清空所有浏览历史吗？',
    success: (res) => {
      if (res.confirm) {
        history.value = [];
        message.value.show({
          type: 'success',
          title: '已清空',
          duration: 1000,
        });
      }
    },
  });
}
</script>

<template>
  <view class="min-h-screen bg-gray-50 pb-[env(safe-area-inset-bottom)]">
    <!-- 顶部标题（修改为历史记录风格） -->
    <view class="bg-gradient-to-r from-blue-600 to-cyan-500 px-6 py-4 rounded-b-lg shadow relative">
      <view class="flex flex-col">
        <view class="flex justify-between items-start">
          <text class="text-2xl font-bold text-white">
            浏览历史
          </text>
          <button
            class="text-xs bg-white/20 text-white px-3 py-1 rounded-full absolute right-4 top-4"
            @click.stop="clearHistory"
          >
            清空记录
          </button>
        </view>
        <view class="text-sm text-white/80 mt-1">
          共 {{ history.length }} 条浏览记录
        </view>
      </view>
    </view>

    <!-- 历史记录列表 -->
    <scroll-view
      scroll-y
      class="h-[calc(100vh-7.5rem)] px-2 py-3"
      :refresher-enabled="true"
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onPullDownRefresh"
    >
      <!-- 空状态 -->
      <view v-if="history.length === 0" class="flex flex-col items-center justify-center py-20">
        <image src="/static/images/empty-history.png" class="w-40 h-40 opacity-60 mb-6" />
        <text class="text-lg text-gray-600 mb-1">
          暂无浏览记录
        </text>
        <text class="text-sm text-gray-400 mb-6">
          浏览过的文章会出现在这里
        </text>
        <button
          class="bg-gradient-to-r from-blue-600 to-cyan-500 text-white rounded-full px-8 py-2 text-sm"
          @click="uni.switchTab({ url: '/pages/home/index' })"
        >
          去首页发现
        </button>
      </view>

      <!-- 历史记录卡片 -->
      <view
        v-for="(item, index) in history"
        :key="item.id"
        class="bg-white rounded-xl shadow-sm mb-4 flex relative overflow-hidden active:scale-[0.98] transition-transform duration-100"
        @click="navigateToDetail(item.id)"
      >
        <!-- 左侧时间轴 -->
        <view
          class="absolute left-0 top-0 bottom-0 w-1.5"
          :class="{
            'bg-blue-500': index === 0,
            'bg-gray-300': index > 0,
          }"
        />

        <!-- 封面图 -->
        <image
          :src="item.cover"
          class="w-28 h-28 rounded-lg m-3 ml-4 object-cover"
          mode="aspectFill"
        />

        <!-- 内容区域 -->
        <view class="flex-1 flex flex-col py-3 pr-1">
          <!-- 标题（未读加粗） -->
          <text
            class="text-lg font-bold line-clamp-2 leading-tight mb-2"
            :class="item.isRead ? 'text-gray-800' : 'text-gray-900'"
          >
            {{ item.title }}
          </text>

          <!-- 作者信息 + 浏览时间 -->
          <view class="flex flex-col mb-2">
            <view class="flex items-center">
              <image :src="item.avatar" class="w-5 h-5 rounded-full mr-2" />
              <text class="text-sm text-gray-600">
                {{ item.author }}
              </text>
            </view>
            <text class="text-xs text-gray-400 mt-1">
              {{ item.viewTime }}
            </text>
          </view>

          <!-- 底部信息行 -->
          <view class="flex items-center justify-between mt-1">
            <view class="flex items-center space-x-3">
              <view class="flex items-center text-xs text-gray-500">
                <uni-icons type="clock" size="14" class="text-gray-400" />
                <text class="ml-1">
                  {{ item.readTime }}
                </text>
              </view>
            </view>

            <!-- 分类标签 -->
            <text class="text-xs text-blue-700 bg-blue-100 px-2 py-0.5 rounded-full">
              {{ item.category }}
            </text>
          </view>
        </view>

        <!-- 未读标记 -->
        <view
          v-if="!item.isRead"
          class="absolute top-2 right-2 w-2 h-2 bg-red-500 rounded-full"
        />
      </view>

      <!-- 加载状态 -->
      <view v-if="isLoading" class="flex justify-center items-center py-6">
        <uni-icons type="spinner-cycle" size="20" class="text-gray-400 animate-spin" />
        <text class="text-sm text-gray-500 ml-2">
          加载更多记录...
        </text>
      </view>

      <view v-if="!hasMore && history.length > 0" class="flex justify-center items-center py-6">
        <text class="text-sm text-gray-500">
          已经到底啦~
        </text>
      </view>
    </scroll-view>
    <CustomMessage ref="message" />
  </view>
</template>
